#include "QRONode_P.h"

static void parentUpdateImp(QRONode::Private* _P,int target, int parent);

void QRONode::Private::handleParentPacket(QVariant value)
{
    QVariantList list = value.toList();
    for(auto i:list)
    {
        auto data = i.toList();
        ObjectID target = data[0].value<ObjectID>();
        ObjectID parent = data[1].value<ObjectID>();
        parentUpdateImp(this,target,parent);
    }
}

void QRONode::Private::onParentUpdate(int target, int parent)
{
    parentUpdateImp(this,target,parent);
}

void QRONode::Private::onPushParent(QObject *target, QObject *parent)
{
    auto localTarget = m_objectIdMap.value(target);
    auto localParent = m_objectIdMap.value(parent);
    if(parent && !localParent) return;

    auto remoteTarget = m_remoteIdMapper.key(localTarget);
    auto remoteParent = m_remoteIdMapper.key(localParent);

    if(remoteTarget == NullID) return;

    m_channel->pushParent(remoteTarget,remoteParent);
}

static void parentUpdateImp(QRONode::Private* _P,int target, int parent)
{
    auto localTarget = _P->m_remoteIdMapper.value(target,NullID);
    if(!localTarget) return;
    auto targetData = _P->m_objectDataMap.value(localTarget);
    auto targetObj = targetData->obj;
    if(targetObj == NULL) return;

    QObject* parentObj = NULL;

    if(parent != NullID)
    {
        auto localParent = _P->m_remoteIdMapper.value(parent,NullID);
        auto parentData = _P->m_objectDataMap.value(localParent);
        parentObj = parentData->obj;
    }

    auto rometa = QRemoteObject2Meta::Instance()->fetchRemoteClass(targetObj->metaObject()->className());
    rometa->hierarchyInterface->setParent(targetObj,parentObj);
}
